package com.hnevc.xiaoming.util;

import android.util.Log;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {
    private static OkHttpUtil okHttpUtil;
    private OkHttpClient okHttpClient;
    private MediaType type;
    private Gson gson;
    private static final String HEAD_URL = "";

    private OkHttpUtil() {
        okHttpClient = new OkHttpClient();
        type = MediaType.parse("application/x-www-form-urlencoded");
        gson = new Gson();
    }

    public static OkHttpUtil getOkHttpUtil() {
        if (okHttpUtil == null) okHttpUtil = new OkHttpUtil();
        return okHttpUtil;
    }

    public <T> T sendPostReq(String url, String body, Class<T> tClass) throws IOException {
        RequestBody requestBody = RequestBody.create(type, body);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(HEAD_URL + url)
                .build();

        Response response = null;

        response = okHttpClient.newCall(request).execute();
        T t = gson.fromJson(response.body().string(), tClass);
        return t;
    }

    public Response sendPostReq(String url, String body) throws IOException {

        RequestBody requestBody = RequestBody.create(type, body);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(HEAD_URL + url)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        return response;

    }

    public <T> T sendPostReq(String url, Class<T> tClass) throws IOException {
        RequestBody requestBody = RequestBody.create(type, "");
        Request request = new Request.Builder()
                .post(requestBody)
                .url(HEAD_URL + url)
                .build();

        Response response = okHttpClient.newCall(request).execute();
        T t = gson.fromJson(response.body().string(), tClass);
        return t;
    }
}
